from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
#重定向用的
from django.core.urlresolvers import reverse
#数据分页模块
from django.core.paginator import Paginator
#Q模糊查询
from django.db.models import Q
from .. import models
import time,os
def tab():
	goods = models.Goods.objects.extra(select = {'newpath':'concat(path,id)'}).order_by('newpath')

	return goods

def goodslist(request):
	goods = tab()
	types=request.GET.get('types')
	search=request.GET.get('search')
	print(types,search)
	

	# 实例化分页类
	if types == "all":
		pro = models.Goods.objects.get(cname=search)
		goods = models.Goods.objects.filter(Q(id__contains=search)|Q(cname__contains=search)|Q(upid__contains=pro.id))
	elif types == "cid":
		goods = models.Goods.objects.filter(id__contains=search)
	elif types == "cname":
		goods = models.Goods.objects.filter(Q(cname__contains=search)|Q(upid__contains=pro.id))
	for i in goods:
		num = i.path.count(",") - 1
		i.num=range(num)
		if i.upid == 0:
			i.level="--父类--"
		else:
			g = models.Goods.objects.get(id=i.upid)
			i.level = g.cname	

	p = Paginator(goods,2)
	#获取总的页码数
	sumpage=p.num_pages
	#分页操作
	# 获取当前页码
	page= int(request.GET.get('p',1))
	#判断页码设定位置
	if page < 4:
		#获取迭代页码数据
		prange = p.page_range[:5]
	elif page > sumpage-2:
		prange = p.page_range[-5:]
	elif page >3:
		prange = p.page_range[page-3:page+2]

	# 获取分页数据
	goods = p.page(page)
	return render(request,"myadmin/cate/goodslist.html",{"goodlist":goods,"prange":prange,"page":page,"sumpage":sumpage})

def addgoods(request):
	if request.method == "GET":
		goods = tab()
		return render(request,"myadmin/cate/addgoods.html",{"goods":goods})
	elif request.method == "POST":
		pid=int(request.POST.get('pid'))
		cname=request.POST.get('cname')
		print(pid,cname)
		if pid == 0:
			info = models.Goods()
			info.cname=cname
			info.upid=pid
			info.path="0,"
			info.save()
			return HttpResponse("<script>alert('添加成功');location.href='"+reverse('myadmin_goodslist')+"'</script>")
		else :
			fa = models.Goods.objects.get(id=pid)
			info = models.Goods()
			info.cname=cname
			info.upid=pid
			info.path=fa.path+str(pid)+","
			info.save()
			return HttpResponse("<script>alert('添加成功');location.href='"+reverse('myadmin_goodslist')+"'</script>")		

def delgoods(request):
	# 接受id
	pid = int(request.GET.get('pid'))
	# 判断有没有子分类
	cnum = models.Goods.objects.filter(upid=pid).count()
	if cnum:
		return JsonResponse({'msg':0})
	else:
		c = models.Goods.objects.get(id=pid)
		c.delete()
		return JsonResponse({'msg':1})
def rename(request):
	pid = int(request.GET.get("id"))
	newname = request.GET.get("msg")
	print(pid,newname)
	try:
		goods = models.Goods.objects.get(id=pid)
		goods.cname=newname
		goods.save()
		return JsonResponse({'data':1})
	except:
		return JsonResponse({'data':0})



	